package com.itany.action;

import com.itany.exception.ServiceExecpion;
import com.itany.jdbc.factory.ObjectFactory;
import com.itany.jdbc.util.CommonUtil;
import com.itany.pojo.User;
import com.itany.service.UserService;
import com.itany.service.proxy.ProxyTransaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 陈华旺
 * @version 1.0
 * @date 2023年11月23日 15:51
 * @Description TODO
 */
@WebServlet("/login")
public class LoginAction extends HttpServlet {

    private UserService us = ObjectFactory.getObj("UserService");
    private UserService usProxy = ObjectFactory.getProxy("UserService",new ProxyTransaction(us));

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String reqCode = req.getParameter("code");
        try {
            HttpSession session = req.getSession();
            String code = (String) session.getAttribute("code");
            if(!reqCode.equals(code)){
                throw new ServiceExecpion("code error");
            }

            User u = usProxy.login(username, CommonUtil.md5ToBase64(password));
//            通过session记录用户登录状态
            session.setAttribute("user",u);
            req.getRequestDispatcher("/WEB-INF/home.jsp").forward(req,resp);
        } catch (ServiceExecpion e){
            e.printStackTrace();
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }
    }
}





